<template>
  <el-dialog title="人员选择" :close-on-click-modal="false" :visible.sync="visible" @close="clearDataList()" width="90vw" top="5vh" append-to-body>
    <el-container>
      <el-main style="height:70vh;overflow-x: hidden;">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="24" :md="5">
            <div class="boxsty">
              <el-tree :data="treeData" :props="defaultProps" :filter-node-method="filterNode" class="filter-tree" node-key="id" highlight-current :default-expanded-keys="[1]" accordion @node-click="getNodeData" />
            </div>
          </el-col>
          <el-col :xs="24" :sm="24" :md="7">
            <div class="boxsty">
              <div class="flex titbottom">
                <el-input v-model="listQuery.name" placeholder="请输入搜索用户" style="margin-right:10px"></el-input>

                <el-button @click="btnSearch" type="primary" icon="el-icon-search" plain>搜索</el-button>

              </div>
              <div class="avue-crud">
              <el-table @row-click="handleClick" :data="tableDataDept" v-loading="tableloading" style="width: 100%">
                <!-- <el-table-column fixed prop="userId" label="Id" width="80">-->
                <!--/el-table-column>-->
                <el-table-column prop="username" label="用户" width="120">
                </el-table-column>
                <el-table-column prop="ryName" label="姓名" min-width="150">
                </el-table-column>
                <!--               <el-table-column fixed="right" label="操作" width="100">-->
                <!--                <template slot-scope="scope">-->
                <!--                  <el-button @click="handleClick(scope.row)" type="text" size="small">添加</el-button>-->
                <!--                </template>-->
                <!--               </el-table-column>-->
              </el-table>
              </div>
              <div style="margin-top:20px">
                <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="page.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="page.pageSize" :total="page.total" background layout="total, sizes, prev, pager, next">
                  <!-- , jumper -->
                </el-pagination>
              </div>
            </div>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12">
            <div class="boxsty">
              <div class="tabletext titbottom">已选择人员</div>
              <div class="avue-crud">
              <el-table :data="tableDataUser" ref="ry-table" stripe>
                <el-table-column prop="userName" label="姓名" width="100">
                </el-table-column>
                <el-table-column prop="deptName" label="部门" min-width="220">
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="100">
                  <template slot-scope="scope">
                    <el-button @click="delUserList(scope.$index)" type="danger" plain>删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
    <span slot="footer" class="dialog-footer">
      <!-- <el-button type="primary" @click="exportExcel" style="float: left">导出已选人员</el-button> -->
      
      <el-button type="primary" v-if="canSubmit" @click="btnSave">确定</el-button>
      <el-button type="primary" plain @click="btnCancel">取消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { fetchTree } from '@/api/admin/dept'
import { fetchList } from '@/api/admin/user'
import { selHzBmList, savelist, removeByHzId } from '@/api/ceping/cepinghzgldxpzb'

export default {
  data() {
    return {
      qjDeptId: '', //全局部门id
      qjGzId: "", //全局规则id
      tableloading: false, //table遮挡
      visible: false,
      canSubmit: false,
      tableDataDept: [],
      tableDataUser: [],
      dataForm: {},
      listQuery: {
        name: ''
      },
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20, // 每页显示多少条,
        isAsc: false // 是否倒序
      },
      searchForm: {},
      zdySearchForm: {},
    }
  },
  created() {
    this.getList();
  },
  methods: {
    init(id) {
      this.qjGzId = id;
      this.visible = true;
      this.canSubmit = true;
      this.loadTableDataUser(id);
    },
    //查询被测评对象
    loadTableDataUser(id) {
      selHzBmList(id).then(data => {
        var obj = data.data.data;
        if (obj) {
          for (var i = 0; i < obj.length; i++) {
            this.tableDataUser.push({
              id: obj[i].id,
              hzId: obj[i].hzId,
              userId: obj[i].userId,
              userName: obj[i].userName,
              deptId: obj[i].deptId,
              deptName: obj[i].deptName,
              userZw: obj[i].userZw,
              userLx: obj[i].userLx,
              userDeptId: obj[i].userDeptId,
              userDeptName: obj[i].userDeptName,
              bhzPx: obj[i].bhzPx,
            });
          }
        }
      }).catch(() => {
        this.$notify.error('数据错误')
      });
    },
    getList() {
      fetchTree(this.listQuery).then(response => {
        this.treeData = response.data.data
      })
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    getPersons(page, params) {
      this.tableloading = true;

      fetchList(Object.assign({
        current: page.currentPage,
        size: page.pageSize
      }, params, this.searchForm, this.zdySearchForm)).then(response => {
        // this.list = response.data.data.records
        this.tableDataDept = response.data.data.records

        this.page.total = response.data.data.total
        this.tableloading = false;
        ////console.log(this.tableDataDept);
      }).catch(err => {
        this.tableloading = false;
      })
    },
    getNodeData(data) {
      this.page.currentPage = 1
      this.qjDeptId = data.id;

      this.getPersons(this.page, {
        deptId: data.id
      })
    },
    //选人添加到右边的框
    handleClick(vm) {
      for (var i = 0; i < this.tableDataUser.length; i++) {
        if (this.tableDataUser[i].userId == vm.userId) {
          return;
        }
      }
      let objUser = {};
      objUser["hzId"] = this.qjGzId;
      objUser["userId"] = vm.userId;
      objUser["userName"] = vm.ryName;
      objUser["deptId"] = vm.deptId;
      objUser["deptName"] = vm.deptName;
      objUser["userZw"] = vm.ryZw;
      objUser["userLx"] = "个人";

      this.tableDataUser.push(objUser);
    },
    //删除人员list
    delUserList(index) {
      this.tableDataUser.splice(index, 1);
    },
    //清空记录
    clearDataList() {
      this.qjDeptId = '';
      this.tableDataDept = [];
      this.tableDataUser = [];
    },
    //保存人员
    btnSave() {
      this.canSubmit = false;
      if (this.tableDataUser.length == 0) {
        removeByHzId(this.qjGzId).then(data => {
          this.$notify.success('操作成功')
          this.visible = false
          this.$emit('refreshDataList')
        }).catch(() => {
          this.canSubmit = true;
        });
      } else {
        savelist(this.tableDataUser).then(data => {
          this.$notify.success('操作成功')
          this.visible = false
          this.$emit('refreshDataList')
        }).catch(() => {
          this.canSubmit = true;
        });
      }
    },
    // tree搜索事件,搜索人
    btnSearch() {
      let param = {
        deptId: this.qjDeptId
      }

      if (this.listQuery.name.trim() !== '') {
        param['username'] = this.listQuery.name.trim();
        param['ryName'] = this.listQuery.name.trim();
      }
      this.getPageUsers(param);
    },
    // 分页
    // 每页数
    sizeChangeHandle(val) {
      this.page.pageSize = val
      this.page.currentPage = 1
      this.getPageUsers()
    },
    // 当前页
    currentChangeHandle(val) {
      this.page.currentPage = val
      this.getPageUsers()
    },
    //分页刷新
    getPageUsers(vm) {
      if (vm) {
        this.getPersons(this.page, vm)
      } else {
        this.getPersons(this.page, {
          deptId: this.qjDeptId
        })
      }
    },
    //取消按钮
    btnCancel() {
      this.visible = false;
      this.clearDataList();
    },
    /**
     * excel 导出
     */
    exportExcel() {
      try {
        // 导出
        require.ensure([], () => {
          const {
            export_json_to_excel
          } = require("@/util/Export2Excel");
          const tHeader = "用户,姓名,部门".split(",");
          const filterVal = "xsUserName,ryName,deptName".split(",");
          const list = this.tableDataUser.map(column =>
            filterVal.map(header => {
              return column[header];
            })
          );
          export_json_to_excel(tHeader, list, "已选人员名单");
        });
      } catch (e) {
        if (typeof console !== 'undefined') console.error(e)
      }
    }
  }
}

</script>

<style scoped>
</style>
